<?php


namespace App\Http\Services;


use App\YaoUserPostLog;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
use Requests;
use Lcobucci\JWT\Configuration;

class YaoUserCenter
{
    protected $host             = 'http://120.24.75.216:9203/';
    protected $wxRegOrLogUrl    = 'member/wechatRegisterOrLogin';
    protected $getUserInfoUrl   = 'member/getMemberInfo';
    protected $syncUserInfoUrl  = 'member/syncMemberInfo';
    public function __construct()
    {
        $this->wxRegOrLogUrl    = $this->host.$this->wxRegOrLogUrl;
        $this->getUserInfoUrl   = $this->host.$this->getUserInfoUrl;
        $this->syncUserInfoUrl  = $this->host.$this->syncUserInfoUrl;
    }


    /**
     * 用户通过第三方微信小程序授权进行会员信息操作（注册/登录）
     * @param $phone
     * @param $name
     * @param $program_name
     * @param $ip
     * @return bool|string
     */
    public function userWechatRegOrLoginInYaoSystem($phone,$name,$program_name,$ip){
        $url = $this->wxRegOrLogUrl;
        $payload = [
            'phoneNum'              => $phone,
            'memberName'            => $name,
            'memberRegisterSource'  => $program_name,
            'ipAddress'             => ip2long($ip),
        ];
//        $response = Requests::post($url,['Content-Type'=>'application/json'],$payload);
        $client = new Client();
        try {
            $response = $client->request('POST', $url, ['Content-Type' => 'application/json', 'body' => json_encode($payload)]);
        } catch (GuzzleException $e) {
            \Log::error("GuzzleExceptionERROR:userWechatRegOrLoginInYaoSystem");
            return false;
        }
        YaoUserPostLog::addLog($url,$payload,$response);
        if ($response->getStatusCode() != 200)
            return false;

        if (!$response->getBody())
            return false;
        $data = json_decode($response->getBody());
        if (isset($data->code) && $data->code == 200)
            return $data->data->userKey ?? false;
        return false;
    }

    /**
     * 获取会员信息
     * @param $userKey
     * @return bool|string
     */
    public function getUserInfoInYaoSystem($userKey){
        $url = $this->getUserInfoUrl;
        $payload = [
            'userKey'  => $userKey,
        ];
//        $response = Requests::post($url,[],$payload);
        $client = new Client();
        try {
            $response = $client->request('POST', $url, ['Content-Type' => 'application/json', 'body' => json_encode($payload)]);
        } catch (GuzzleException $e) {
            \Log::error("GuzzleExceptionERROR:getUserInfoInYaoSystem:".$e->getMessage());
            return false;
        }
        YaoUserPostLog::addLog($url,$payload,$response);
        if ($response->getStatusCode() != 200)
            return false;

        if (!$response->getBody())
            return false;
        $data = json_decode($response->getBody());
        if (isset($data->code) && $data->code == 200)
            return $data->data ?? false;
        return false;
    }

    public function syncUserInfoToYaoSystem($name,$phone,$email,$head_img_url,$sex,$age,$area,$home_address){
        $url = $this->syncUserInfoUrl;
        $payload = [
            'phoneNum'              => $phone,
            'memberName'            => $name,
            'memberEmail'           => $email ?? '',
            'memberHeadImg'         => $head_img_url ?? '',
            'memberSex'             => $sex ?? 0,
            'memberAge'             => $age ?? 0,
            'memberAddress'         => $area ?? '',
            'home_address'          => $home_address ?? '',
        ];
        $client = new Client();
        try {
            $response = $client->request('POST', $url, ['Content-Type' => 'application/json', 'body' => json_encode($payload)]);
        } catch (GuzzleException $e) {
            \Log::error("GuzzleExceptionERROR:syncUserInfoToYaoSystem".$e->getMessage());
            return false;
        }
        YaoUserPostLog::addLog($url,$payload,$response);
        if ($response->getStatusCode() != 200)
            return false;

        if (!$response->getBody())
            return false;
        $data = json_decode($response->getBody());
        if (isset($data->code) && $data->code == 200)
            return $data->data->userKey ?? false;
        return false;
    }

    /**
     * @param $userKey
     * @return array|bool
     */
    public function jwtHandler($userKey){
        try {
            $config = Configuration::forUnsecuredSigner();
            $claims = $config->parser()->parse($userKey)->claims();
            $claims = (array)$claims;
            $aud_array = array_shift($claims);
            $key = $aud_array['aud'][0];
            $array = explode('|',$key);
            return $array;
        } catch (\Exception $exception) {
            return false;
        }
    }
}